// miniprogram/pages/my/my.js
const db = wx.cloud.database()
const admin = db.collection('admin')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
    const userInfo = app.globalData.userInfo
    if (userInfo) {
    admin.where({
      openid:userInfo.openid
    }).count().then(res => {
      userInfo.isadmin = res.total
      
        this.setData({
          userInfo: userInfo
        })
     
    })
      .catch(err => {
        console.error(err)
      })
  }
    
   
    /*wx.getSetting({
      success: res => {
        console.log("-----" + res.authSetting['scope.userInfo'])
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          console.log("已授权" + res.authSetting['scope.userInfo'])
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
              console.log(Object.keys(this.data.userInfo).length)
            }
          })
        }
      }
    })*/
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const userInfo = app.globalData.userInfo
    if (userInfo) {
    admin.where({
      openid: userInfo.openid
    }).count().then(res => {
        userInfo.isadmin = res.total
        this.setData({
          userInfo: userInfo
        })
      
    })
      .catch(err => {
        console.error(err)
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const userInfo = app.globalData.userInfo
    if (userInfo) {
      admin.where({
        openid: userInfo.openid
      }).count().then(res => {
        userInfo.isadmin = res.total
        this.setData({
          userInfo: userInfo
        })

      })
        .catch(err => {
          console.error(err)
        })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onGotUserInfo: function (result) {
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        console.log(res.result.dbResult.total)
        result.detail.userInfo.openid = res.result.OPENID
        result.detail.userInfo.isadmin = res.result.dbResult.total
        app.globalData.userInfo = result.detail.userInfo
        this.setData({
          userInfo: result.detail.userInfo
        })
        wx.setStorageSync("userInfo", result.detail.userInfo)
      }
    })
  }
})